package com.thread.thread02;
/**
 * 关键字synchronized取得的锁都是对象锁，而不是把一段代码（方法）当做锁，
 * 所以代码中哪个线程先执行synchronized关键字的方法，哪个线程就持有该方法所属对象的锁（Lock）
 * 在静态方法上加synchronized关键字，表示锁定.class类，类一级别的锁（独占.class类）。
 *
 */
public class MyThread{

	private static int num=0;
	public static synchronized void printNum(String tag) throws InterruptedException {
		if("a".equals(tag)) {
			num = 100;
			System.out.println("tag a, set num over!");
			Thread.sleep(1000);
		}else {
			num = 200;
			System.out.println("tag b, set num over!");
		}
		System.out.println("tag= " +tag + "  num = "+ num);
	}
	
	public static void main(String[] args) {
		MyThread m1 = new MyThread();
		MyThread m2 = new MyThread();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					m1.printNum("a");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
		},"t1");
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					m2.printNum("b");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
		},"t2");
		t1.start();
		t2.start();
	}
}
